#include "GateClientHandler.h"
#include "JME_GLog.h"

void GateClientHandler::sessionConnectSucceed( JME_TcpSessionPtr session )
{
	static int _clientId = 1;

	session->start(_clientId++);

	_clientMap[session->getNetId()] = session;

	LOGT("Client from [ %s:%s:%d ] connected", session->getIp(), session->getPort(), session->getNetId());
}

void GateClientHandler::sessionConnectFailed( JME_TcpSessionPtr session, boost::system::error_code e )
{

}

void GateClientHandler::sessionDisconnect( JME_TcpSessionPtr session, boost::system::error_code e )
{
	session->stop();

	_clientMap.erase(session->getNetId());

	LOGT("Client from [ %s:%s:%d ] disconnect", session->getIp(), session->getPort(), session->getNetId());
}

void GateClientHandler::sessionReceiveMessage( JME_TcpSessionPtr session, JME_Message::JME_MessagePtr msg )
{
	Dispatcher.execMessageHandler(msg->_msgId, session, msg);
}

void GateClientHandler::sessionReadError( JME_TcpSessionPtr session, boost::system::error_code e )
{
	session->stop();

	_clientMap.erase(session->getNetId());

	LOGT("Client from [ %s:%s:%d ] disconnect", session->getIp(), session->getPort(), session->getNetId());
}

void GateClientHandler::sendClientMsg(int net, const JME_Message& msg)
{
	auto it = _clientMap.find(net);
	if (it != _clientMap.end())
	{
		it->second->writeMessage(msg);
	}
}
